// controller project controller.go
package controller

import (
	"crypto/md5"
	"encoding/hex"
	"net/http"
	"restful-api-demo/db"
	"restful-api-demo/model"

	"github.com/gin-gonic/gin"
)

// md5加密
func md5Password(str string) string {
	h := md5.New()
	h.Write([]byte(str))
	return hex.EncodeToString(h.Sum(nil))
}

// 创建新用户
func CreateUser(c *gin.Context) {
	name := c.PostForm("name")   //获取POST请求参数name
	phone := c.PostForm("phone") //获取POST请求参数phone
	user := model.User{
		Phone:    phone,
		Name:     name,
		Password: md5Password("666666"), //用户密码
	}
	db.GORM.Save(&user) //保存到数据库
	c.JSON(
		http.StatusCreated,
		gin.H{
			"status":  http.StatusCreated,
			"message": "User created successfully!",
			"ID":      user.ID,
		}) //返回状态到客户端
}

// 获取所有用户
func FetchAllUser(c *gin.Context) {
	var user []model.User        //定义一个数组去数据库总获取数据
	var _userRes []model.UserRes //定义一个响应数组用户返回数据到客户端

	db.GORM.Find(&user)

	if len(user) <= 0 {
		c.JSON(
			http.StatusNotFound,
			gin.H{
				"status":  http.StatusNotFound,
				"message": "No user found!",
			})
		return
	}

	//循环遍历，追加到响应数组
	for _, item := range user {
		_userRes = append(_userRes,
			model.UserRes{
				ID:    item.ID,
				Phone: item.Phone,
				Name:  item.Name,
			})
	}
	//返回状态到客户端
	c.JSON(http.StatusOK,
		gin.H{"status": http.StatusOK,
			"data": _userRes,
		})
}

// 获取单个用户
func FetchUser(c *gin.Context) {
	var user model.User //定义User结构体
	ID := c.Param("id") //获取参数id

	db.GORM.First(&user, ID)

	if user.ID == 0 { //如果用户不存在，则返回
		c.JSON(http.StatusNotFound,
			gin.H{"status": http.StatusNotFound, "message": "No user found!"})
		return
	}

	//返回响应结构体
	res := model.UserRes{ID: user.ID, Phone: user.Phone, Name: user.Name}
	c.JSON(http.StatusOK, gin.H{"status": http.StatusOK, "data": res})
}

// 更新用户
func UpdateUser(c *gin.Context) {
	var user model.User          //定义User结构体
	userID := c.Param("id")      //获取参数id
	db.GORM.First(&user, userID) //查找数据库

	if user.ID == 0 { //如果数据库不存在，则返回
		c.JSON(http.StatusNotFound,
			gin.H{"status": http.StatusNotFound, "message": "No user found!"})
		return
	}

	//更新对应的字段值
	db.GORM.Model(&user).Update("name", c.PostForm("name"))
	db.GORM.Model(&user).Update("phone", c.PostForm("phone"))

	c.JSON(http.StatusOK,
		gin.H{"status": http.StatusOK, "message": "Updated User successfully!"})
}

// 删除用户
func DeleteUser(c *gin.Context) {
	var user model.User     //定义User结构体
	userID := c.Param("id") //获取参数id

	db.GORM.First(&user, userID) //查找数据库

	if user.ID == 0 { //如果数据库不存在，则返回
		c.JSON(http.StatusNotFound,
			gin.H{"status": http.StatusNotFound, "message": "No user found!"})
		return
	}

	//删除用户
	db.GORM.Delete(&user)
	c.JSON(http.StatusOK,
		gin.H{"status": http.StatusOK, "message": "User deleted successfully!"})
}
